package com.tanhua.controller;

import com.tanhua.exception.BusinessException;
import com.tanhua.model.domain.ErrorResult;
import com.tanhua.server.UserServiceApi;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@RestController
@RequestMapping("/user")
public class LoginController {
    @Autowired
    private UserServiceApi userService;

    @PostMapping("login")
    public ResponseEntity login(@RequestBody Map<String, String> param) {
        //1. 获取手机号
        String phone = param.get("phone");
        //2. 发送验证码
        userService.sendCode(phone);
        //3. 返回数据
        return ResponseEntity.ok("验证码发送成功");
    }

    @PostMapping("loginVerification")
    public ResponseEntity loginVerification(@RequestBody Map<String, String> param) {
        try {
            String phone = param.get("phone");
            String verificationCode = param.get("verificationCode");
            Map user = userService.findUser(phone, verificationCode);
            return ResponseEntity.ok(user);
        } catch (BusinessException be) {
            ErrorResult errorResult = be.getErrorResult();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResult);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(ErrorResult.error());
        }
    }
}

